package com.udi.project.business.upload.diup.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.nostra13.universalimageloader.utils.L;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.udi.common.exception.base.BaseException;
import com.udi.common.utils.security.ShiroUtils;
import com.udi.framework.aspectj.lang.annotation.Log;
import com.udi.framework.aspectj.lang.enums.BusinessType;
import com.udi.framework.web.domain.AjaxResult;
import com.udi.project.business.base.domain.BaseCorpVo;
import com.udi.project.business.local.di.thread.Submit;
import com.udi.project.business.upload.diup.domain.*;
import com.udi.project.business.upload.diup.mapper.GetDiupMesMapper;
import com.udi.project.business.upload.diup.service.GetDiupMesService;
import com.udi.project.business.utils.httpApi.OkHttp1;
import com.udi.project.business.utils.redis.RedisUtils;
import com.udi.project.system.user.domain.User;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GetDiupMesServiceImpl implements GetDiupMesService{

    @Autowired
    GetDiupMesMapper getDiupMesMapper;

    /** 申报接口*/
    @Autowired
    private OkHttp1 okHttp1;

    /** redis工具*/
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 查询完整的di信息，下拉补全，根据名称获得规格，从而获得最小销售单元产品标识
     * @param name
    [di]* @return java.util.List<com.udi.project.business.upload.diup.domain.dt_di_indentityVo>
     * @author yuxin
     * @date 2021/10/15 16:15
     */
    @Override
    public JSONObject getDiup(String name) {
        JSONObject ob = new JSONObject();
        try {
            List<dt_di_indentityVo> lists = getDiupMesMapper.getDiup(name);
            JSONArray array = new JSONArray();
            for (dt_di_indentityVo list : lists) {
                JSONObject obj = new JSONObject();
                obj.put("cpbs",list.getZXXSDYCPBS());
                obj.put("ggxh",list.getGGXH());
                obj.put("cpmc",list.getCPMCTYMC());
                array.add(obj);
            }
            ob.put("code",1);
            ob.put("data",array);
            return ob;
        }catch (BaseException e){
            ob.put("code",0);
            ob.put("data",e.getMessage());
            return ob;
        }
    }

    /**
     *
     * @param data 获取diup完整信息显示
    [data]* @return java.util.List<com.udi.project.business.upload.diup.domain.dt_di_indentityVo>
     * @author yuxin
     * @creed: Talk is cheap,show me the code
     * @date 2021/10/18 8:32
     */
    @Override
    public List<dt_di_indentityVo> getDiupMes(dt_di_indentityVo data) {
        return getDiupMesMapper.getDiupMes(data);
    }



    /**
     * @param Id 根据Id查询DeviceData
     * @return DeviceData
     */
    @Override
    public DeviceData getDeviceDataById(Integer Id) {
        return getDiupMesMapper.getDeviceDataById(Id);
    }

    /**
     * @param Id 根据最小销售单元查询DevicePackage列表
     * @return DevicePackage
     */
    @Override
    public List<DevicePackage> getDevicePackageById(String Id) {
        List<DevicePackage> devicePackageList= getDiupMesMapper.getDevicePackageListById(Id);

        for (int i = 0; i < devicePackageList.size(); i++) {
            devicePackageList.get(i).setId(i+1);
        }
        return devicePackageList;
    }

    /**
     * @param Id 根据最小销售单元查询DeviceStorage列表
     * @return DeviceStorage
     */
    @Override
    public List<DeviceStorage> getDeviceStorageById(String Id) {
        List<DeviceStorage> deviceStorageList = getDiupMesMapper.getDeviceStorageListById(Id);
        for (int i = 0; i < deviceStorageList.size(); i++) {
            deviceStorageList.get(i).setId(i+1);
        }
        return deviceStorageList;
    }

    /**
     * @param Id 根据最小销售单元查询DeviceClinical列表
     * @return DeviceClinical
     */
    @Override
    public List<DeviceClinical> getDeviceClinicalById(String Id) {
        List<DeviceClinical> deviceClinicalList = getDiupMesMapper.getDeviceClinicalListById(Id);
        for (int i = 0; i < deviceClinicalList.size(); i++) {
            deviceClinicalList.get(i).setId(i+1);
        }
        return deviceClinicalList;
    }



    /**
     * @param baseData 网页填报添加操作，添加数据回滚操作,一个表没添加成功其余数据回滚
     * @author yuxin
     * @creed: Talk is cheap,show me the code
     * @date 2021/10/18 14:29
     */
    @Transactional
    @Override
    public AjaxResult addData(BaseData baseData) {
        Integer statu1 = 0,statu2 = 0,statu3 = 0,statu4 = 0;
        try {
            DeviceData deviceData = baseData.getDeviceData();
            //设置初始条件
            deviceData.setStatu("0");
            deviceData.setUploadType("add");
            deviceData.setDel_flag("0");
            //根据当前用户绑定的部门获取统一社会信用代码
            BaseCorpVo baseCorpVo = getDiupMesMapper.getCurrDtBaseCorp(ShiroUtils.getUserId());
            deviceData.setTYSHXYDM(baseCorpVo.getTyshxydm());
            //开始插入
            statu1 = getDiupMesMapper.insertDeviceData(deviceData);
            statu2 = getDiupMesMapper.insertDevicePackage(baseData.getDevicePackage());
            statu3 = getDiupMesMapper.insertDeviceStorage(baseData.getDeviceStorage());
            statu4 = getDiupMesMapper.insertDeviceClinical(baseData.getDeviceClinical());

            if(statu1 == 1 && statu2 == 1&& statu3 == 1&& statu4 == 1){
                return AjaxResult.success("插入成功！");
            }else{
                return AjaxResult.error("插入失败！");
            }
        }catch(RuntimeException e){
            e.printStackTrace();
            //手动抛出异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
           return AjaxResult.error(e.getMessage());
        }
    }



    /**
     * @param id diup编辑操作
     *           [data]* @return java.lang.Integer
     * @author yuxin
     * @creed: Talk is cheap,show me the code
     * @date 2021/10/18 14:29
     */
    @Override
    public Integer editData(Integer id) {
        return null;
    }

    /**
     * @param data diup去除操作
     *             [data]* @return java.lang.Integer
     * @author yuxin
     * @creed: Talk is cheap,show me the code
     * @date 2021/10/18 14:29
     */
    @Override
    public Integer removeData(String data) {
        return null;
    }

    /**
     * @param data diup永久删除操作
     *             [data]* @return java.lang.Integer
     * @author yuxin
     * @creed: Talk is cheap,show me the code
     * @date 2021/10/18 14:29
     */
    @Override
    public Integer delData(String data) {
        return null;
    }


    /**
     * @param ids 数组字符串,数据填报验证
     *            [ids]* @return int
     * @author yuxin
     * @creed: Talk is cheap,show me the code
     * @date 2021/10/8 17:37
     */
    @Override
    public JSONObject checkByIds(List<Product> ids)  throws Exception {

        List<Object> array = new ArrayList<>();
        Data_Set data_set = new Data_Set();
        //数据依次查询，封装处理
        for (Product idd : ids) {
            List<Product> list = getDiupMesMapper.getProductList(idd.getZXXSDYCPBS());
            List<DevicePackage> pro1 = getDiupMesMapper.getDevicePackageList(idd.getZXXSDYCPBS());
            List<DeviceStorage> pro2 = getDiupMesMapper.getDeviceStorageList(idd.getZXXSDYCPBS());
            List<DeviceClinical> pro3 = getDiupMesMapper.getDeviceClinicalList(idd.getZXXSDYCPBS());
            for (Product p:list) {
                p.setDevicePackageList(pro1);
                p.setDeviceStorageList(pro2);
                p.setDeviceClinicalList(pro3);
            }
            array.add(list.get(0));
        }

        data_set.setAccessToken(okHttp1.getToken("Token"));
        data_set.setDataSet(array);

        redisUtils.set("ids",data_set.toString());
        //测试数据
        //String st = "{\"accessToken\":\"EC66BA0713D3AE3B1675CB55571B49C0CBE970E28433C828FA9E313D9D917AD38916446CE067BB2A636065394741694648B0C49DA51F31DD6FF8E6E516C42C4809CEF68260BCE53820902F59A4179FB15B76A97EDB1EC32B55F878824D9411B09D19915D59D21370\",\"dataSet\":[{\"bGSM\":\"\",\"BSZT\":\"1,2\",\"BTCPBS\":\"\",\"BTCPBSYZXXSDYCPBSSFYZ\":\"\",\"CGZMRAQXGXX\":\"3\",\"CPBSBMTXMC\":\"GS1\",\"CPBSFBRQ\":\"2021-10-14\",\"CPHHHBH\":\"\",\"CPLX\":\"1\",\"CPMCTYMC\":\"合成可吸收性外科缝线\",\"CPMS\":\"asd\",\"deviceClinicalList\":[{\"CCDW\":\"\",\"CCZ\":\"\",\"lCSYCCLX\":\"\"},{\"CCDW\":\"cm\",\"CCZ\":\"1\",\"lCSYCCLX\":\"长度\"}],\"devicePackageList\":[{\"BZCPBS\":\"\",\"BZNHXYJBZCPBS\":\"\",\"BZNHXYJCPBSSL\":\"\",\"cPBZJB\":\"\"}],\"deviceStorageList\":[{\"CCHCZTJ\":\"\",\"JLDW\":\"\",\"ZDZ\":\"\",\"ZGZ\":\"\"},{\"cCHCZTJ\":\"温度\",\"jLDW\":\"℃\",\"zDZ\":\"10\",\"zGZ\":\"20\"}],\"di_identity_id\":84,\"FLBM\":\"01-00-00\",\"GGXH\":\"GMM632L\",\"HCHZSB\":\"1\",\"MJFS\":\"\",\"QTXXDWZLJ\":\"\",\"SCBSSFBHPH\":\"0\",\"SCBSSFBHSCRQ\":\"0\",\"sCBSSFBHSXRQ\":\"0\",\"SCBSSFBHXLH\":\"0\",\"SFBJWYCXSY\":\"0\",\"SFWBLZTLCP\":\"1\",\"SFWWJBZ\":\"1\",\"SFYBTZJBS\":\"0\",\"SFYZCBAYZ\":\"1\",\"SPMC\":\"合成可吸收性外科缝线\",\"SYDYCPBS\":\"\",\"SYQSFXYJXMJ\":\"0\",\"TSCCHCZTJ\":\"\",\"TSCCSM\":\"\",\"TSRQ\":\"\",\"TYSHXYDM\":\"916101315784432974\",\"uploadType\":\"add\",\"YBBM\":\"\",\"YFLBM\":\"\",\"YLQXZCRBARMC\":\"李xx\",\"YLQXZCRBARYWMC\":\"\",\"ZCBACPBS\":\"\",\"ZCZBHHZBAPZBH\":\"916101315784432974\",\"ZDCFSYCS\":\"10\",\"ZXXSDYCPBS\":\"06901240100410\",\"ZXXSDYZSYDYDSL\":\"1\"}]}";
        System.out.println("最终提交数据----------》"+data_set);
        JSONObject msg =  okHttp1.PostProductFillIn(data_set.toString());
        System.out.println("------msg"+msg);
        return msg;
    }


    /**
     *
     * @Description:数据标识填报
     * @param what 填报表单  检测重复数据
     * @return: com.udi.framework.web.domain.AjaxResult
     * @Date: 2021/8/11 9:51
     */
    @Log(title = "DI申报", businessType = BusinessType.OTHER)
    @Override
    public AjaxResult declare(Product1 what) throws IOException {
        int i=0;
        String STR = "{\"di_id\":\"null\",\"use\":\"null\",\"accessToken\":\"F0D36169A4227793431411032809A07C5F746FF6CC81366D3C4B2DF019E605E545D77EADF0ED0AFEBF67393A145B2DF69E937734E9ECE1A29D499B1FDF1E3363A79358D53E51EB05C9EE8D0C513911594EC970AD87282543FCFD29B8156CE95F14D4C0D5CA6BFDA6\",\"dataSet\":[{\"uploadType\":\"add\",\"deviceRecordKey\":\"null\",\"ZXXSDYCPBS\":\"1690312359669\",\"ZXXSDYZSYDYDSL\":\"10\",\"SYDYCPBS\":\"null\",\"CPBSBMTXMC\":\"GS1\",\"SFYBTZJBS\":\"1\",\"BTCPBSYZXXSDYCPBSSFYZ\":\"1\",\"BTCPBS\":\"null\",\"BSZT\":\"1\",\"SFYZCBAYZ\":\"1\",\"ZCBACPBS\":\"null\",\"CPBSFBRQ\":\"null\",\"CPMCTYMC\":\"null\",\"GGXH\":\"null\",\"SFWBLZTLCP\":\"null\",\"CPMS\":\"null\",\"CPHHHBH\":\"null\",\"CPLX\":\"null\",\"FLBM\":\"null\",\"YFLBM\":\"null\",\"YLQXZCRBARMC\":\"null\",\"YLQXZCRBARYWMC\":\"null\",\"TYSHXYDM\":\"null\",\"ZCZBHHZBAPZBH\":\"null\",\"SFBJWYCXSY\":\"null\",\"ZDCFSYCS\":\"null\",\"SFWWJBZ\":\"null\",\"SYQSFXYJXMJ\":\"null\",\"MJFS\":\"null\",\"YBBM\":\"null\",\"CGZMRAQXGXX\":\"null\",\"devicePackage\":[{\"BZCPBS\":\"null\",\"BZNHXYJCPBSSL\":\"null\",\"CPBZJB\":\"null\"}],\"deviceStorage\":[{\"CCHCZTJ\":\"null\",\"ZDZ\":\"null\",\"ZGZ\":\"null\",\"JLDW\":\"null\"}],\"TSCCHCZTJ\":\"null\",\"deviceClinical\":[{\"LCSYCCLX\":\"null\",\"CCZ\":\"null\",\"CCDW\":\"null\"}],\"TSCCSM\":\"null\",\"SCBSSFBHPH\":\"null\",\"SCBSSFBHXLH\":\"null\",\"SCBSSFBHSCRQ\":\"null\",\"SCBSSFBHSXRQ\":\"null\",\"QTXXDWZLJ\":\"null\",\"TSRQ\":\"null\",\"BGSM\":\"null\"}]}";
        if(okHttp1.ConnectivityTest()){
            JSONObject jsonObject =null;
            //注入Token
            what.setAccessToken(okHttp1.getToken("Token"));
            jsonObject = okHttp1.PostProductFillIn(what.toString());
            if(jsonObject.getString("returnCode").equals("1")){

                redisUtils.lSet("serial",jsonObject.getString("deviceRecordKey"));
                redisUtils.lSet("logo",jsonObject.getString("ZXXSDYCPBS"));

            }else {
                System.out.println("报错信息----------eeeee------->"+jsonObject);
                System.out.println("报错信息----------------->"+jsonObject.getString("returnMsg"));
                return AjaxResult.error(jsonObject.getString("returnMsg"));
            }

            /** 需要序列化反序列化 存储对象*/
            redisUtils.SetObject("list",what);

            //启用子线程提交申报
            /** 成功后解析 标识数据库记录编号 最小销售单元产品标识*/
            Map<String,Object> keyMap = new HashMap<>(50);
            JSONArray jsonArray =jsonObject.getJSONArray("successList");
            for(int j=0;j<jsonArray.size();j++){
                JSONObject jsonKey = jsonArray.getJSONObject(j);
                keyMap.put(jsonKey.getString("deviceRecordKey"),jsonKey.getString("ZXXSDYCPBS"));
            }
            redisUtils.hmset("deviceRecordKey",keyMap);

            /**如果子线程报出：提交产品标识发生错误异常，则需要重新填写一遍*/
            Submit submit = new Submit();
            submit.start();
        }else {
            return AjaxResult.error("无法连接医疗器械唯一标识数据库，请稍后再试......");
        }
        return AjaxResult.success("提交成功,正在进行后续完善中...");
    }
}
